package leetcode.code0791;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public String customSortString2(String order, String s) {
		int[] seq = new int[26];
		char[] o = order.toCharArray();
		for (int i = 0, j = 1; i < order.length(); i++, j++) {
			seq[o[i] - 'a'] = j;
		}
		Character[] ss = new Character[s.length()];
		char[] cs = s.toCharArray();
		for (int i = 0; i < cs.length; i++) {
			ss[i] = cs[i];
		}
		Arrays.sort(ss, (a, b) -> seq[a - 'a'] - seq[b - 'a']);
		for (int i = 0; i < cs.length; i++) {
			cs[i] = ss[i];
		}
		return new String(cs);
	}

	public String customSortString(String order, String s) {
		int[][] seq = new int[26][3];
		char[] o = order.toCharArray();
		for (int i = 0; i < 26; i++) {
			seq[i][2] = i;
		}
		for (int i = 0, j = 1; i < order.length(); i++, j++) {
			seq[o[i] - 'a'][0] = j;

		}
		char[] cs = s.toCharArray();
		for (int i = 0; i < cs.length; i++) {
			seq[cs[i] - 'a'][1]++;
		}
		Arrays.sort(seq, (a, b) -> a[0] - b[0]);
		for (int i = 0, p = 0; i < 26; i++) {
			int[] se = seq[i];
			if (se[1] != 0) {
				char c = (char) (se[2] + 'a');
				for (int j = 0; j < se[1]; j++, p++) {
					cs[p] = c;
				}
			}
		}
		return new String(cs);
	}

	@Override
	public void debug4() {
		H.compare("cbad", this.customSortString("cba", "abcd"));
		H.compare("cbad", this.customSortString2("cba", "abcd"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
